<template>
    <el-dialog v-model="showDialog" title="导入数据" @close="close" style="width: 30%">
            <el-form ref="dataFrom" :rules="rules" :model="form" label-width="100px" align="center">
                <el-upload
                            ref="uploadRef"
                            class="upload-demo"
                            action="/api/user/importUsers"
                            :auto-upload="false"
                            :before-upload="beforeUpload"
                           :on-success = onSuccess
                           :on-error = onError
                    >
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>
                        &nbsp;
                        <el-button class="ml-3" type="success" @click="doImportSubmit">
                            导入
                        </el-button>

                        <template #tip>
                            <div class="el-upload__tip">
                                必须是xlsx或xls格式!，文件大小不能大于5MB!
                            </div>
                        </template>
                    </el-upload>
            </el-form>
    </el-dialog>
</template>

<script setup>
    import {ref,reactive,onBeforeUpdate,onUpdated} from 'vue'
    import request from '@/utils/request.js'
    import { ElMessage } from 'element-plus'
    let uploadRef = ref(null)
    let dataFrom = ref(null)
    const  emits = defineEmits(['close','reload'])
    const rules = reactive({
    })
    let props = defineProps(['open','type','id'])
    let showDialog = ref(false)
    let form = reactive({})
    let uploadSuccess = ref(false)

    onUpdated(function () {
    })

    function close(){
        showDialog.value = false
        dataFrom.value.resetFields()//重置表单校验
    }

    const beforeUpload = (rawFile) => {
        console.log("文件格式："+rawFile.type)
        if (rawFile.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && rawFile.type !== 'application/vnd.ms-excel') {
            ElMessage.error('必须是xlsx或xls格式!')
            return false
        } else if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('文件大小不能大于5MB!')
            return false
        }
        return true
    }

    function doImportSubmit(){
        uploadRef.value.submit()
    }

    function onSuccess(response, uploadFile, uploadFiles){
        ElMessage.success('上传成功!')
        emits("reload")
        showDialog.value = false
        uploadRef.value.clearFiles()
    }

    function onError(error, uploadFile, uploadFiles){
        ElMessage.error("上传失败"+error)
    }

    defineExpose({showDialog})
</script>

<style scoped>

</style>